<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;

class SysPermission extends Model
{
    use HasFactory;

    protected $typeMap = [
        1 => 'CATALOG', 2 => 'MENU', 3 => 'EXTLINK', 4 => 'BUTTON', 5 => 'INTLINK'
    ];

    protected $fillable = [
        'name', 'path', 'perm', 'tree_path', 'type', 'component', 'sort', 'visible', 'icon', 'always_show' ,'keep_alive', 'redirect', 'parent_id'
    ];

    protected $append = ['type_label'];

    public function children()
    {
        return $this->hasMany(SysPermission::class, 'parent_id', 'id')->with('children');
    }

    public function roles()
    {
        return $this->belongsToMany(SysRole::class, SysRolePermission::class);
    }

    public function permissions()
    {
        return $this->belongsToMany(SysPermission::class, SysRolePermission::class);
    }

    protected function type(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => $this->typeMap[$value],
            set: fn (string $value) => array_search($value, $this->typeMap),
        );
    }
}
